import { IPSPanelContainer } from '@ibiz/dynamic-model-api';
import { AppServiceBase } from '../../service';
import { LogUtil } from '../../utils';
import { PanelDetailModel } from './panel-detail';

/**
 * 面板容器模型
 *
 * @export
 * @class PanelContainerModel
 * @extends {PanelDetailModel}
 */
export class PanelContainerModel extends PanelDetailModel {

    /**
     * 数据区域类型
     * @description 值模式 [数据面板模式] {NONE：无、 LOGINFORM：登录表单、 SINGLEDATA：单项数据、 MULTIDATA：多项数据、 INHERIT：继承、 USER：用户自定义 }
     * @type {( string | 'NONE' | 'LOGINFORM' | 'SINGLEDATA' | 'MULTIDATA' | 'INHERIT' | 'USER')} 
     * @default INHERIT
     */
    public dataRegionType: string | 'NONE' | 'LOGINFORM' | 'SINGLEDATA' | 'MULTIDATA' | 'INHERIT' | 'USER' = 'NONE';

    /**
     * 数据源类型
     * @description 值模式 [数据面板源（全部）] {DEACTION：实体行为、 DEDATASET：实体集合、 DELOGIC：实体逻辑 }
     * @type {( string | 'DEACTION' | 'DEDATASET' | 'DELOGIC')} 
     */
    public dataSourceType: string | 'DEACTION' | 'DEDATASET' | 'DELOGIC' = '';

    /**
     * 数据刷新模式
     * @type {number}
     * @default -1
     */
    public reloadTimer: number = -1;

    /**
     * Creates an instance of PanelContainerModel.
     * @param {*} [opts={}]
     * @memberof PanelContainerModel
     */
    constructor(opts: any = {}) {
        super(opts);
        this.dataRegionType = (this.panelItemModel as IPSPanelContainer)?.dataRegionType;
        this.dataSourceType = (this.panelItemModel as IPSPanelContainer)?.dataSourceType;
    }

    /**
     * 执行异步逻辑
     *
     * @memberof PanelContainerModel
     */
    public async loaded() {
        let nullData = {};
        switch (this.dataRegionType) {
            case 'LOGINFORM':
                AppServiceBase.getInstance().setDataAreaState('LOGINFORM', nullData);
                this.data = nullData;
                break;
            case 'INHERIT':
                if (!this.parentItem) {
                    this.data = nullData;
                } else {
                    if (this.parentItem.dataRegionType === 'MULTIDATA' && this.parentItem['data']?.length > 0) {
                        this.data = this.parentItem['data'][this.$index];
                    } else {
                        this.data = this.parentItem.data;
                    }
                }
                break;
            case 'SINGLEDATA':
                this.data = await this.loadData();
                break;
            case 'MULTIDATA':
                this.data = await this.loadData();
                break;
            case 'USER':
                console.log('用户自定义未实现')
                break;
            default:
                break;
        }
    }

    /**
     * 加载数据
     *
     * @memberof PanelContainerModel
     */
    public async loadData(): Promise<any> {
        const deCodeName = (this.panelItemModel as IPSPanelContainer)?.getPSAppDataEntity?.()?.codeName;
        if (this.dataSourceType === 'DEACTION' || this.dataSourceType === 'DEDATASET') {
            const method = (this.panelItemModel as IPSPanelContainer)?.getPSAppDEMethod?.()?.codeName;
            if (deCodeName && method) {
                try {
                    const service = await ___ibz___.gs.getService(deCodeName);
                    if (service && service[method] instanceof Function) {
                        const response = await service[method](this.context, this.viewparams);
                        if (response && response.status === 200) {
                            return response.data;
                        }
                    }
                } catch (error) {
                    LogUtil.error(`面板--- ${this.caption} ---加载数据失败`);
                }
            }
        } else if (this.dataSourceType === 'DELOGIC') {
            const deLogicTag = (this.panelItemModel as IPSPanelContainer).getPSAppDELogic?.()?.codeName;
            if (deCodeName && deLogicTag) {
                try {
                    const service = await ___ibz___.gs.getService(deCodeName);
                    if (service && service.executeAppDELogic instanceof Function) {
                        const data = await service.executeAppDELogic(deLogicTag, this.context, this.viewparams);
                        return data;
                    }
                } catch (error) {
                    LogUtil.error(`面板--- ${this.caption} ---加载数据失败`);
                }
            }
        }
        return {};
    }

    /**
     * 设置数据
     *
     * @param {*} val
     * @memberof PanelContainerModel
     */
    public setData(val: any) {
        const { name, value } = val;
        Object.assign(this.data, { [name]: value });
        if (Object.is(this.dataRegionType, 'LOGINFORM')) {
            AppServiceBase.getInstance().setDataAreaState('LOGINFORM', { key: name, value });
        } else if (Object.is(this.dataRegionType, 'INHERIT')) {
            if (!this.parentItem) {
                return;
            } else {
                this.parentItem.setData(val);
            }
        }
    }

}